package com.zj.project.common.expand

import com.zj.project.common.base.BaseBean
import com.zj.project.common.base.BaseError
import com.zj.project.common.base.BaseViewModel
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.BackpressureStrategy
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.functions.Consumer
import io.reactivex.rxjava3.schedulers.Schedulers
import io.reactivex.rxjava3.subscribers.ResourceSubscriber

/**
 * createTime:2021/8/3 13:39
 * auth:张继
 * des:
 */


fun Disposable.add(viewModel: BaseViewModel) {
    viewModel.addDisposable(this)
}


fun <T> Flowable<BaseBean<T>>.subscribe(
    viewModel: BaseViewModel,
    success: Consumer<T>,
    error: Consumer<BaseError>
) {
    this.observeOn(AndroidSchedulers.mainThread())
        .subscribeOn(Schedulers.io())
        .unsubscribeOn(Schedulers.io())
        .flatMap { bean ->
            if (bean.errorCode == 0) {
                Flowable.create<T>({
                    try {
                        it.onNext(bean.data)
                        it.onComplete()
                    } catch (e: Exception) {
                        it.onError(e)
                    }
                }, BackpressureStrategy.BUFFER)
            } else {
                Flowable.error(BaseError(bean.errorCode,bean.errorMsg))
            }
        }
        .subscribeWith(object : ResourceSubscriber<T>() {
            override fun onStart() {
                super.onStart()
            }
            override fun onNext(t: T) {
                success.accept(t)
            }
            override fun onError(t: Throwable) {
                if (t is BaseError) {
                    error.accept(t)
                }else{
                    error.accept(BaseError(-1,t.message!!))
                }
            }
            override fun onComplete() {
            }
        }).add(viewModel)


}